﻿using UnityEngine;
using System.IO;
using System.Xml;
using System;
using System.Collections;
using UnityEngine.Networking;
using System.Xml.Serialization;
using UnityModule;
using LuaFramework;
using SDK.Scripts.App;
using SDK.Scripts.Plat;
using SimpleJson;

[Serializable]
public enum ResourceMode
{
    /// <summary>
    /// 编辑器下不使用bundle,不用打bundle运行
    /// 只有在编辑器下用的
    /// </summary>
    EditorLocalRes,

    /// <summary>
    /// 用本地Bundle模式不更新
    /// </summary>
    LocalBundle,

    /// <summary>
    /// 更新bundle流程
    /// </summary>
    UpdateableBundle,
}
public class UpdateSettings : MonoBehaviour
{
    public static GameSetting GameSetting;
    public static UpdateSettings Instance;
    public string UpdateUrl = String.Empty;
    public string ServerHost;

    //当前平台资源下载路径
    public string CdnUrl { get; private set; }
    public void Awake()
    {
        Instance = this;
        if(Application.platform == RuntimePlatform.WindowsPlayer)
        {
            Screen.SetResolution(1280,720, false);
        }
    }

    private void Start()
    {
        StartCoroutine(GetRunningSetting());
    }

    public bool IsOfficial()
    {
        return string.IsNullOrEmpty(ServerHost);
    }
    public void SetCdnRootUrl(string cdnRoot)
    {
        CdnUrl = cdnRoot.TrimEnd('/') + "/" + ApplicationPath.PlatformName + "/";
    }

    //---------- 加载/修改配置文件 ----------

    private const string SettingFileName = "Dev_Setting.xml";

    IEnumerator GetRunningSetting()
    {
        UnityWebRequest webRequest = UnityWebRequest.Get(SettingFilePath(true));
        yield return webRequest.SendWebRequest();
        //Debug.LogError("webRequest.downloadHandler.text: " + webRequest.downloadHandler.text);

        XmlDocument doc = new XmlDocument();
        doc.LoadXml(webRequest.downloadHandler.data.RemoveUTF8Bom().ToUTF8());
        GameSetting = ReadXml<GameSetting>(doc.OuterXml);

        UpdateUrl = GameSetting.UpdateHost;
        ServerHost = GameSetting.ServerHost;
        CdnUrl = UpdateUrl;
        Debug.Log($"UpdateSettings Init result: {GameSetting.emResType}\nURL: {UpdateUrl}\nServerHost: {ServerHost}");

        yield return null;
        yield return null;
        yield return null;
        SDK.Scripts.App.GameSDK.Run();
        yield return null;
        PanelLoad.Instance.SetProgress(0.2f);
        yield return null;
        long userid = 0;

        if(long.TryParse(PlayerPrefs.GetString("UserID64"),out userid))
        {
            SDK.Scripts.App.GameSDK.GamePlat.UserID = userid;
        }
        // SDK.Scripts.App.GameSDK.GamePlat.UserID = PlayerPrefs.GetInt("UserID");
        //Debug.LogError(PlayerPrefs.GetString("UserID64")+" "+userid);
        AppInit();
        yield return null;
        SDK.Scripts.App.GameSDK.GamePlat.DoAction(1123);
        
        PanelLoad.Instance.SetProgress(0.4f);
        PanelLoad.Instance.ShowKF(SDK.Scripts.App.GameSDK.GamePlat.Channel);
        yield return null;
        ResourceComponent.Instance.Init(() => {
            LuaHelper.GetLuaManager().InitStart();
        });
    }

    [System.Serializable]
    public class DomainStr
    {
        public string domain;
    }
    [System.Serializable]
    public class DomainJson
    {
        public DomainStr[] domains;
    }

    private void AppInit()
    {
        SDKPlatCfg cfg = new SDKPlatCfg(0, 0);
        cfg.appKey = GameSetting.appKey;
        cfg.appId = GameSetting.appId;
        cfg.gameId = GameSetting.gameId;
        cfg.domain = GameSetting.domain;
        cfg.channel = GameSetting.channel;
        cfg.gameVersion = GameSetting.gameVersion;
        cfg.gameConfVersion = GameSetting.gameUrlVersion;

        string domainCfg = SDK.Scripts.App.GameSDK.GamePlat.DoAction(142);
        if (domainCfg != "") {
        //     string json = "[{\"domain\":\"12317wan.cn\"},{\"domain\":\"12317wan.com.cn\"},{\"domain\":\"chanyou001.com\"}]";
            string json2 = "{\"domains\":" + domainCfg + "}";

            DomainJson domainJson = JsonUtility.FromJson<DomainJson>(json2);
            Debug.LogError(domainJson.domains[0].domain);

            cfg.domain = domainJson.domains[0].domain;
        }
    
        SDK.Scripts.App.GameSDK.GamePlat.Init(cfg);
    }

    //读取xml中的设置
    public static T ReadXml<T>(string xmlStr)
    {
        XmlSerializer serializer = new XmlSerializer(typeof(T));
        StringReader sr = new StringReader(xmlStr);
        T obj = (T)serializer.Deserialize(sr);
        sr.Close();
        return obj;
    }

    public static string SettingFilePath(bool isWebRequest = false)
    {
        if (isWebRequest)
        {
            return Path.Combine(ApplicationPath.StreamingAssetsPath, SettingFileName);
        }
        return Path.Combine(Application.streamingAssetsPath, SettingFileName);
    }
}
//等下次能出包再改
[Serializable, XmlRoot("Config")]
public class GameSetting
{
    public string UpdateHost;
    public string ServerHost;
    [XmlIgnore]
    public ResourceMode emResType;
    public int ResType
    {
        set
        {
            emResType = (ResourceMode)value;
        }
        get
        {
            return (int)emResType;
        }
    }

    public int gameUrlVersion;
    public string appKey;
    public string appId;
    public int gameId;   
    public string domain;
    public string channel;
    public int gameVersion;
}